
//封装Promise请求，返回Promise实例
const ajax = function(method,url,data){
    const request = new XMLHttpRequest();
    return new Promise(function(resolve,reject){
        request.onreadystatechange = ()=>{
            if(request.readyState !== 4){return};
            if(request.status === 200){
                resolve(request.responseText);
            }else{
                reject(request.status);
            }
        };
        request.open(method,url);
        if(method == 'get'){
            request.send();
        }else{
            request.setRequestHeader("Content-Type", "application/json");
            request.send(JSON.stringify(data));
        }
    });
};


$(function(){
    let ad = new Chat();
    ad.init();
})


function Chat(){

    let $this = this;
    this.init=()=>{

        //绑定删除一项
        $(document).on("click", ".container .messageList li i", function(ev){ 
            let name = $(this).parent().children('span').eq(0).html();
            let message = $(this).parent().children('span').eq(1).html();
            console.log('name='+name+",message="+message);
            var o = {};
            o.name = name;
            o.message = message;
            $this.delete(o);
        });

         //绑定删除全部
        $(document).on("click", "#btn-delete-all", function(e){ 
            $this.clearall();
        });

        //绑定全部显示
        $(document).on("click", "#btn-view", function(e){ 
            $this.list();
        });
       
        //绑定查询单条留言
        $(document).on("click", ".container .messageList li", function(e){ 
            let name = $(this).children('span').eq(0).html();
            let message = $(this).children('span').eq(1).html();
            console.log('name='+name+",message="+message);
            var o = {};
            o.name = name;
            o.message = message;
            $this.load(o);
        });
        

        //绑定添加/修改(服务端使用map,添加与删除流程一致,key唯一)
        $("#btn-add,#btn-modify").click(function(){
            let _nickname = $(".container .nickname").val();
            let _content = $(".container .msg-content").val();
            if(_nickname=="" || _content==""){
                alert("请输入信息");
                return;
            }
            let o = {};
            o.name = _nickname;
            o.message = _content
            $this.add(o);
        });
    };

    //显示列表
    this.list = ()=>{
        ajax('get','/list/get','')
        .then(result=>{
            this.render(result);
        }).catch(error=>{
            alert('error='+error);
        });
    };

    //添加留言
    this.add = (data)=>{
        ajax('post','/list/add',data)
        .then(()=>{
            return  ajax('get','/list/get');
        }).then( result =>{
            this.render(result);
        })
        .catch( error=>{
            alert('error='+error);
        });
    };

    //清除全部留言
    this.clearall = ()=>{
        ajax('get','/list/clear','')
        .then(result=>{
            this.render(result);
        }).catch(error=>{
            alert('error='+error);
        });
    };

    //删除单条留言
    this.delete = (data)=>{
        ajax('post','/list/delete',data)
        .then(result=>{
            this.render(result);
        }).catch(error=>{
            alert('error='+error);
        });
    };

    //加载单条留言
    this.load = (data)=>{
        ajax('post','/list/load',data)
        .then(result=>{
            let o = JSON.parse(result);
            $(".container .nickname").val(o.name);
            $(".container .msg-content").val(o.message);
        }).catch(error=>{
            alert('error='+error);
        });
    };

    //渲染页面
    this.render = (result)=>{
        $(".container .messageList").html("");
        JSON.parse(result).forEach(element => {
            let chat2 = `<li class=list-group-item> <span>${element.key}</span> <b>说</b> <span>${element.value}</span> <i class="es ht-delete float-right"></i>  </li>`;
            $(".container .messageList").append(chat2);
        });
    };
}

